<template>
    <el-dialog v-model="dialogFormVisible" @close="handleClose" :close-on-click-modal="false" :title="title" width="940px">
        <el-form 
            v-loading="editLoading" 
            ref="formRef" 
            label-width="200px"
            :model="form" 
            style="padding: 30px" 
            :rules="rules"
        >
            <el-form-item label="会员级别名称：" required prop="levelName">
                <el-input v-model="form.levelName" autocomplete="off" maxlength="60" placeholder="请输入会员卡名" />
            </el-form-item>
            <el-form-item label="卡片封面图：" required prop="cover">
              <kva-upload @success="handleUploadSuccess" ref="imgUploadRef"></kva-upload>
              <p class="ml10" style="margin-left: 10px">建议的图片尺寸：826(宽)*250(高)</p>
            </el-form-item>
            <el-form-item label="有限期（天）：" required prop="levelCycle">
                <el-input-number v-model="form.levelCycle" style="width: 50%" autocomplete="off" maxlength="20" placeholder="请输入有限期，输入'-1' 表示永久 "  controls-position="right"/>
            </el-form-item>

            <el-form-item label="原价（元）：" required prop="levelOriginalPrice">
                <el-input-number v-model="form.levelOriginalPrice" style="width: 50%" autocomplete="off" maxlength="20" placeholder="请输入原价金额"  controls-position="right" />
            </el-form-item>

            <el-form-item label="现价（元）：" required prop="levelPrice">
                <el-input-number v-model="form.levelPrice" style="width: 50%" autocomplete="off" maxlength="20" placeholder="请输入现价金额"  controls-position="right" />
            </el-form-item>

            <el-form-item label="会员权益：" required >
              <el-checkbox-group v-model="checkList"  >
                <el-checkbox v-for="(item) in authorityList"  :label="item.id" :key="item.id">
                  {{item.permissionName}}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>

            <el-form-item label="备注："  prop="levelDesc">
              <el-input v-model="form.levelDesc" autocomplete="off" maxlength="400" placeholder="请输入备注内容"  type="textarea" />
            </el-form-item>

            <el-form-item label="启用状态："  prop="status">
              <el-radio-group v-model="form.status">
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>

          <div class="dialog-footer" style="text-align: center">
                <el-button @click="handleClose" icon="remove">取消</el-button>
                <el-button type="primary" :loading="suLoading" @click="handleSubmit" icon="plus">{{ form.id?'更新':'保存' }}</el-button>
            </div>
        </el-form>
    </el-dialog>
</template>
<script setup>
import { saveUpdate, getById } from '@/api/users/index.js'
import KVA from '@/utils/kva.js'
import debounce from '@/utils/debounce'
const emits = defineEmits(["load"])
const imgUploadRef = ref({
  isshow: false,
})
// 控制弹窗得显示
const dialogFormVisible = ref(false)
const checkList = ref([])
// 这个数据模型
let form = ref({

})

const authorityList = ref([])
// 弹出标题
const title = ref("添加")
const editLoading = ref(false)
const suLoading = ref(false)
// 表单ref, 用于提交最终得验证处理
const formRef = ref({})
// 表单验证
const rules = reactive({
  "levelName": [{required: true, message: '请输入会员卡名', trigger: 'blur'}],
  "levelCycle": [{required: true, message: '请输入有限期（天）', trigger: 'blur'}],
  "levelPrice": [{required: true, message: '请输入现价', trigger: 'blur'}],
  "levelOriginalPrice": [{required: true, message: '请输入原价', trigger: 'blur'}],
  "cover": [{required: true, message: '请上传封面', trigger: 'blur'}],
})

// 打开修改密码的弹窗
const handleOpen = async (opid) => {
    // 每次打开头重置
    dialogFormVisible.value = true;
    title.value = "添加"
    if (opid) {
        title.value = "编辑"
        editLoading.value = true;
        const resp = await getById(opid)
        editLoading.value = false;
        form.value = resp.data
        title.value = "编辑【" + form.value.userName + "】"
    }

}

// 保存和修改
const handleSubmit = () => {
  suLoading.value = true
  debounce(()=>{
    formRef.value.validate(async (valid, fields) => {
      if (valid) {
        try{
          form.value.authorityIds = checkList.value.join(",")
          await saveUpdate(form.value)
          suLoading.value = false
          // 提示保存成功
          KVA.notifySuccess(form.value.id?"更新成功":"保存成功")
          // 关闭弹窗
          handleClose()
          // 刷新方法
          emits("load")
        }catch(ex){
          suLoading.value = false
        }
      }else{
        suLoading.value = false
      }
    })
  },600)
}

const handleClose = () => {
    form.value = {
      id: "",
      level: "",
      levelName: "",
      cover:"",
      levelDesc: "",
      levelCycle: "",
      levelPrice: "",
      levelOriginalPrice: "",
      status:1,
      authorityIds:"",

      levelAuthorityDesc: "",
      levelCommunityAuthorityDesc: "",
      levelTimeType: "",
      levelTimeDesc: "",
      memberType: "1",
    }
    checkList.value = []
    formRef.value.resetFields()
    suLoading.value = false
    editLoading.value = false
    dialogFormVisible.value = false
}

// 上传封面回调
const handleUploadSuccess = (data1, data2) => {
  form.value.cover = data1
}
// 把弹出打开得方法暴露给父组件进行调用
defineExpose({
    handleOpen
})
</script>